package com.put.mybills.activities;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.nhaarman.listviewanimations.itemmanipulation.OnDismissCallback;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissAdapter;
import com.nhaarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.put.mybills.R;
import com.put.mybills.adapter.GlobalParams;
import com.put.mybills.adapter.NewFactureAdapter;
import com.put.mybills.adapter.NotPaidBillsAdapter;
import com.put.mybills.model.Bill;
import com.put.mybills.model.Facture;

public class HomeFragment extends Fragment implements OnDismissCallback {
	
	private String TAG = "HomeFragment";
	private NewFactureAdapter newFacturesAdapter;
	private NotPaidBillsAdapter notPaidBillAdapter;
	private List<Facture> factures;	
	private List<Bill> bills;	
	private LinearLayout lineralLayout;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
			
		View rootView = inflater.inflate(R.layout.fragment_home, container, false);		
		lineralLayout = (LinearLayout)rootView.findViewById(R.id.empty_noty_list);		
		ListView newFactures = (ListView) rootView.findViewById(R.id.new_factures);			
		ListView listOfNotPaid = (ListView) rootView.findViewById(R.id.not_paid_factures);			
		Calendar cal = Calendar.getInstance();
		factures = serachBills(cal.getTime(),1);		
		Log.d(TAG, "Factures count = " + factures.size());	
		
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());	
		
		if (factures.size()>0){		
			lineralLayout.setVisibility(lineralLayout.GONE);			
			Boolean switcher = sharedPreferences.getBoolean("read_facture_icon", false);
			newFacturesAdapter = new NewFactureAdapter(getActivity(),factures,true,switcher);
			//SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(new SwipeDismissAdapter(newFacturesAdapter, this));
			//swingBottomInAnimationAdapter.setInitialDelayMillis(300);
			//swingBottomInAnimationAdapter.setAbsListView(newFactures);
			newFactures.setAdapter(newFacturesAdapter);
			newFacturesAdapter.addAll(getFactureItems());	
			
			newFactures.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {					
					Intent intent = new Intent(getActivity(), FactureActivity.class);	        	 
		        	intent.putExtra("FactureName", factures.get(position).getName());
		        	getActivity().startActivity(intent);  
				}});
			
			
		} 		
		
		bills = searchNotPaidBill();
		if (bills.size() > 0) {
			lineralLayout.setVisibility(lineralLayout.GONE);			
			notPaidBillAdapter = new NotPaidBillsAdapter(getActivity(),bills);
			SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(new SwipeDismissAdapter(notPaidBillAdapter, this));
			swingBottomInAnimationAdapter.setInitialDelayMillis(300);
			swingBottomInAnimationAdapter.setAbsListView(listOfNotPaid);
			listOfNotPaid.setAdapter(swingBottomInAnimationAdapter);
			notPaidBillAdapter.addAll(getBillItems());	
			
			
			listOfNotPaid.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {								
					Intent intent = new Intent(getActivity(), BillActivity.class);	        	 
		        	intent.putExtra("BillName", bills.get(position).getName());
		        	getActivity().startActivity(intent);  
				}});			
		}

		return rootView;	
		
	}
	
	private ArrayList<Integer> getFactureItems() {
		ArrayList<Integer> items = new ArrayList<Integer>();
		for (int i = 0; i < factures.size(); i++) {
			items.add(i);
		}
		return items;
	}
	
	private ArrayList<Integer> getBillItems() {
		ArrayList<Integer> items = new ArrayList<Integer>();
		for (int i = 0; i < bills.size(); i++) {
			items.add(i);
		}
		return items;
	}
	
	
	@Override
	public void onDismiss(AbsListView listView, final int[] reverseSortedPositions) {
		for (int position : reverseSortedPositions) {
			Bill tmp = bills.get(position);
			tmp.setIfPaid(1);
			GlobalParams.getInstance().billdatasource.updateBill(tmp);
			notPaidBillAdapter.remove(position);
			bills.remove(position);
		}
	}
	
	public List<Facture> serachBills(Date currentDate, Integer interval) {
 		
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 		List<Facture> machtedBills = new ArrayList<Facture>(); 		
 		List<Facture> factures = GlobalParams.getInstance().facturedatasource.getAllFactures();
 		for (Facture facture : factures) { 			
 			List<Bill> bills = GlobalParams.getInstance().billdatasource.getAllBills(facture.getId()); 			
 			Collections.sort(bills); 			
 			if (bills.size()>0) {
 				Bill bill = bills.get(bills.size()-1); 				
				Date billDate = null;
				try {
					billDate = sdf.parse( bill.getDate());
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				if (facture.getInterval() == 0)
					continue;
				
				Calendar cal = Calendar.getInstance();  
				cal.setTime(billDate);  
				cal.add(Calendar.MONTH, facture.getInterval()); 
				  
				int diffInDays = (int)( (cal.getTime().getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24) );
				
				if (diffInDays <= 5 && diffInDays >= 0){
					int yes = 0;
					for (Bill bill2 : bills) {
						if(bill.getTmpDate().getMonth() == cal.getTime().getMonth()){
							yes = 1;
							break;
						}
					}
					
					if (yes==0) {
						//Log.d(TAG,"Nowa przyszla faktura");
						machtedBills.add(facture);
					}
				}				 			
 			}	
		} 
 		
 		return machtedBills;
 	}
	
	public List<Bill> searchNotPaidBill() {
		
		List<Bill> machtedBills = new ArrayList<Bill>(); 		
 		List<Facture> factures = GlobalParams.getInstance().facturedatasource.getAllFactures();
 		for (Facture facture : factures) {
 			
 			List<Bill> bills = GlobalParams.getInstance().billdatasource.getAllBills(facture.getId()); 			
 			Collections.sort(bills);
 			
 			for (Bill bill : bills) {
				if (bill.getIfPaid() == 0)
					machtedBills.add(bill);
			} 			
 		} 		
 		return machtedBills;
	}
	

}
